%%% worker_utils.erl

-module(worker_utils).
-export([build_command/3, command_line_args/1, spawn_workers/1]).

build_command(Job_ID, Task, javac) ->
    Compile_Cmd = "javac " ++ atom_to_list(Job_ID) ++ "wc.java",
    Execute_Cmd = "java "  ++ atom_to_list(Job_ID) ++ "wc " ++ command_line_args(Task),
    {Compile_Cmd, Execute_Cmd};

build_command(Job_ID, Task, g++)   ->
    Compile_Cmd = "g++ "     ++ atom_to_list(Job_ID) ++ "wc.cpp",
    Execute_Cmd = "./a.out " ++ command_line_args(Task),
    {Compile_Cmd, Execute_Cmd};

build_command(Job_ID, Task, gcc)   ->
    Compile_Cmd = "gcc "     ++ atom_to_list(Job_ID) ++ "wc.c",
    Execute_Cmd = "./a.out " ++ command_line_args(Task),
    {Compile_Cmd, Execute_Cmd};

build_command(Job_ID, Task, erl)   ->
    Compile_Cmd = "erl -compile "    ++ atom_to_list(Job_ID)    ++ "wc.erl",
    Execute_Cmd = "erl -noshell -s " ++ command_line_args(Task) ++ " -s init stop",
    {Compile_Cmd, Execute_Cmd};

build_command(Job_ID, Task, py)    ->
    Execute_Cmd = "python " ++ atom_to_list(Job_ID) ++ "wc.py " ++ command_line_args(Task),
    {"echo", Execute_Cmd}.

command_line_args(List) -> string:join(List, " ").

spawn_workers(0) -> ok;
spawn_workers(Workers) ->
	cluster_utils:register_process(list_to_atom("worker" ++ integer_to_list(Workers)), cluster_utils:create_process(?MODULE, do_task, [])),
    spawn_workers(Workers-1).

receive_info(task) ->
    receive
        {task, {Job_ID, Server}, {Task_ID, Task, File_Type}} ->
            {ok, {Job_ID, Server}, {Task_ID, Task, File_Type}};
        _ ->
            cluster_utils:print("Bad message...~n"),
			{error, {bad_data}, {bad_data}}
    end.

execute_command(Command) -> os:cmd(Command).
